<template>
  <div class="warp">
    <div class="flexbox">
      <el-upload
        action="/"
        :on-change="uploadChange"
        :auto-upload="false"
        :show-file-list="false"
        accept=".xls, .xlsx"
        :style="{ float: 'left' }"
      >
        <el-button type="primary">上传表格</el-button>
      </el-upload>
      <span class="flexSpan">
        全部数据：{{ storeArray.length }}&nbsp;&nbsp;&nbsp;&nbsp;正确数量：{{
          correctLenght
        }}&nbsp;&nbsp;&nbsp;&nbsp;错误数量：{{ errorLength }}
      </span>
      <div>
        <el-button
          type="primary"
          :loading="butloading"
          @click="submit()"
          :disabled="isDetection"
          >开始检测</el-button
        >
        <el-button
          type="primary"
          @click="exportTable()"
          :disabled="percentage != 100"
          >导出表格</el-button
        >
      </div>
    </div>
    <div class="progress" v-if="percentage != 0">
      <el-progress :percentage="percentage" :stroke-width="10"></el-progress>
    </div>
    <el-table
      :data="tableData"
      border
      max-height="550"
      style="width: 100%"
      empty-text="没有上传文件哟"
    >
      <el-table-column prop="pageId" label="ID"> </el-table-column>
      <el-table-column prop="pageUrl" label="Page url"> </el-table-column>
      <el-table-column prop="downloadUrl" label="软件地址"> </el-table-column>
      <el-table-column prop="appSize" label="软件大小"> </el-table-column>
      <el-table-column prop="pageName" label="网页标题"> </el-table-column>
      <el-table-column prop="appName" label="软件包名称"> </el-table-column>
      <el-table-column prop="appicon" label="软件图标">
        <template #default="scope">
          <img :src="scope.row.appicon" v-if="scope.row.appicon" alt="" />
        </template>
      </el-table-column>
      <el-table-column prop="version" label="软件版本"> </el-table-column>
      <el-table-column prop="result" label="结果" width="80">
        <template #default="scope">
          <span v-if="scope.row.result === 'ok'" class="successText">
            <el-tag
              :type="scope.row.result === 'ok' ? 'success' : 'primary'"
              disable-transitions
              >成功
            </el-tag>
          </span>
          <span v-if="scope.row.result == '等待检测'"> 等待检测 </span>
          <span
            v-if="scope.row.result != '等待检测' && scope.row.result != 'ok'"
            class="errorText"
          >
            <el-tag
              :type="
                scope.row.result != '等待检测' && scope.row.result != 'ok'
                  ? 'danger'
                  : 'primary'
              "
              disable-transitions
              >失败</el-tag
            >
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :hideOnSinglePage="true"
        :pageSize="pageSize"
        :total="storeArray.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
  <!-- <div class="phrase" @click="refresh()">
    <p>
      {{ phrase[0] }}
    </p>
    <p class="phrtext">
      {{ phrase[1] }}
    </p>
  </div> -->
</template>

<script lang="ts">
import { exportTabl } from "../until/file";
import xlsx, { WorkSheet } from "xlsx";
import { defineComponent, ref, onMounted } from "vue";
import axios from "axios";
import { phraselist } from "../until/phrase";
import { notification } from "ant-design-vue";
export default defineComponent({
  setup() {
    let tableData: any = ref([]);
    let tableHead: any = ref([]);
    let butloading = ref<boolean>(false);
    let isDetection = ref<boolean>(true);
    let phrase: any = ref([]);
    let correctLenght: any = ref(0);
    let errorLength: any = ref(0);
    let storeArray: any = ref([]);
    let newArray: any = ref([]);
    let pageSize: any = ref(50);
    let percentage: any = ref("");
    let fileName = "";
    onMounted(() => {
      refresh();
    });
    const refresh = () => {
      let number = random(0, phraselist.length);
      phrase.value = [];
      phraselist[number].forEach((e) => {
        phrase.value.push(e);
      });
      console.log(phrase.value);
    };
    const random = (min: any, max: any) => {
      return Math.floor(Math.random() * (max - min)) + min;
    };
    const arrTrans = (num: any, arr: any) => {
      // 一维数组转换为二维数组
      let iconsArr: any = []; // 声明数组
      arr.forEach((item: any, index: any) => {
        const page = Math.floor(index / num); // 计算该元素为第几个素组内
        if (!iconsArr[page]) {
          // 判断是否存在
          iconsArr[page] = [];
        }
        iconsArr[page].push(item);
      });
      return iconsArr;
    };
    // 导入excelq
    const uploadChange = async (file: any) => {
      let data = await exportTabl(xlsx, file);
      let str = JSON.stringify(data[0][0]);
      fileName = file.name;
      if (str.indexOf("Page url") == -1 && str.indexOf("软件地址") == -1) {
        notification.open({
          message: "请上传规范的Excel表格",
          description: fileName,
          type: "error",
        });
        return;
      }
      data[0].forEach((e: any) => {
        storeArray.value.push({
          pageId: e["ID"],
          pageUrl: e["Page url"],
          appSize: e["软件大小"],
          downloadUrl: e["软件地址"],
          pageName: "等待检测",
          appName: "等待检测",
          appicon: "",
          version: "等待检测",
          result: "等待检测",
        });
      });
      newArray.value = arrTrans(pageSize.value, storeArray.value);
      tableData.value = newArray.value[0];
      processingResult();
      notification.open({
        message: "上传成功",
        description: fileName,
        type: "success",
      });
      isDetection.value = false;
      // console.log(storeArray.value);
    };
    const handleCurrentChange = (val: number) => {
      tableData.value = newArray.value[val - 1];
    };
    const submit = async () => {
      let data = storeArray.value;
      butloading.value = true;
      for (const fn of data) {
        if (fn.flag != "yes") {
          await analysis(fn);
        }
      }
    };
    const analysis = async (e: any) => {
      let p1 = await getH1(e.pageUrl);
      let p2 = await getAppinfo(e.downloadUrl);
      Promise.all([p1, p2])
        .then((result: any) => {
          if (!result[0].data.code) {
            e.pageName = result[0].data.data.h1;
          } else {
            e.pageName = result[0].data.msg;
          }
          if (!result[1].data.code) {
            e.appName = result[1].data.data.name;
            e.appicon = result[1].data.data.icon;
            e.version = result[1].data.data.version;
            e.flag = "yes";
          } else {
            e.appName = "检测失败";
            e.appicon = "检测失败";
            e.version = "检测失败";
            e.flag = "yes";
          }
          if (e.pageName != e.appName) {
            e.result = "error";
            errorLength.value++;
          } else {
            correctLenght.value++;
            e.result = "ok";
          }
          processingResult();
        })
        .catch((error) => {
          e.pageName = "检测失败";
          e.appName = "检测失败";
          e.appicon = "检测失败";
          e.version = "检测失败";
          e.result = "检测失败";
          console.log(error, "error");
        });
    };
    const processingResult = () => {
      if (correctLenght.value + errorLength.value == storeArray.value.length) {
        butloading.value = false;
        isDetection.value = true;
        notification.open({
          message: "" + fileName + "检测完成",
          description:
            "正确数量：" +
            correctLenght.value +
            "  错误数量：" +
            errorLength.value +
            "",

          type: "success",
          duration:null
        });
      }
      let number =
        ((correctLenght.value + errorLength.value) / storeArray.value.length) *
        100;

      percentage.value =
        correctLenght.value + errorLength.value > 0
          ? Math.max(Math.floor(number), 1)
          : 0;
    };
    const getH1 = (url: any) => {
      return new Promise((resolve, reject) => {
        axios
          .get("/api/htmlInfo?url=" + url)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    };
    const getAppinfo = (url: any) => {
      return new Promise((resolve, reject) => {
        axios
          .get("/api/appInfo?url=" + url)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    };

    const exportTable = () => {
      let aoa_cn = [
        [
          "ID",
          "Page url",
          "软件地址",
          "软件大小",
          "网页标题",
          "软件包名称",
          "软件版本",
          "结果",
        ],
      ];
      storeArray.value.forEach((e: any): any => {
        aoa_cn.push([
          e.pageId,
          e.pageUrl,
          e.appSize,
          e.downloadUrl,
          e.pageName,
          e.appName,
          e.version,
          e.result,
        ]);
      });
      let worksheet: WorkSheet = xlsx.utils.aoa_to_sheet(aoa_cn);
      let workbook = xlsx.utils.book_new();
      xlsx.utils.book_append_sheet(workbook, worksheet, "中文");
      xlsx.writeFile(workbook, "解析过程.xls");
    };
    return {
      tableHead,
      tableData,
      phrase,
      pageSize,
      newArray,
      isDetection,
      percentage,
      storeArray,
      handleCurrentChange,
      correctLenght,
      errorLength,
      refresh,
      butloading,
      submit,
      uploadChange,
      exportTable,
    };
  },
});
</script>
<style>
body {
  background: url("../assets/background.svg");
}
</style>

<style lang="less" scoped>
.progress {
  margin-bottom: 10px;
}
.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.flexSpan {
  display: flex;
  align-items: center;
}
.phrase {
  position: absolute;
  left: 50px;
  top: 0px;
  height: 100%;
  padding-top: 80px;
  font-family: cursive;
  writing-mode: vertical-lr;
  font-size: 40px;
  opacity: 0.5;
  cursor: pointer;
}

.phrtext {
  margin-top: 50px;
}
.flexbox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.el-table--border {
  background-color: rgba(0, 0, 0, 0);
}

/deep/ .el-table tr {
  background-color: rgba(0, 0, 0, 0);
}
.warp {
  margin: 0 auto;
  position: relative;
  z-index: 9;
}

.box {
  background: #fff;
  display: flex;
  justify-content: space-between;
  padding: 20px 30px;
  border-radius: 10px 10px 0px 0px;
}

.result {
  width: 100%;
  background: #fff;
  padding: 10px 0px;
  border-radius: 0px 0px 10px 10px;
}

.cardBox {
  height: 340px;
}

.box-card {
  margin-bottom: 20px;
}

.input {
  width: 400px;
}

.paddBox {
  display: flex;
  padding: 10px 0px;
}

.padd_span {
  width: 150px;
  text-align: right;
  margin-right: 10px;
  height: 30px;
}

.padd_content {
  width: 200px;
  color: #717171;
}

img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
}

.el-notification__title {
  font-size: 18px;
}

.el-notification__content {
  font-size: 16px;
}

.phrase {
  position: absolute;
  left: 50px;
  top: 0px;
  padding-top: 80px;
  font-family: cursive;
  writing-mode: vertical-lr;
  font-size: 40px;
  opacity: 0.5;
  cursor: pointer;
}

.phrtext {
  margin-top: 50px;
}

.errorBox {
  display: flex;
  justify-content: center;
  height: 300px;
  align-items: center;
}

.errorBox img {
  width: 100px;
  height: 100px;
}

.errorText {
  color: red;
}

.successText {
  color: rgb(7, 241, 77);
}
</style>
